<template>
    <el-dialog v-model="show" title="添加颜色" width="26%" align-center @close="handleClose">
        <el-form ref="ruleFormRef" :model="ruleForm" :rules="rules" label-width="auto" class="demo-ruleForm"
            status-icon>
            <el-form-item label="颜色展示图" prop="imageUrl">
                <el-upload ref="designSketchRef" :show-file-list="false" drag :action="uploadImgUrl" :headers="headers"
                    multiple :auto-upload="true" :on-success="handleDesignSketchSuccess"
                    :before-upload="beforedeSignSketchUpload">
                    <img style="height: 100px;" v-if="ruleForm.imageUrl" :src="ruleForm.imageUrl" />
                    <template v-else>
                        <div style="padding-top: 10px;">
                            <uploadStyle type="1" icon="PictureFilled" />
                        </div>
                    </template>
                </el-upload>
            </el-form-item>
            <el-form-item label="十六进制颜色" prop="color">
                <el-input v-model="ruleForm.color" placeholder="比如: #FFFFFF" style="width: 200px;" />
            </el-form-item>
            <el-form-item label="名称" prop="attributeName">
                <el-input v-model="ruleForm.attributeName" placeholder="请输入名称" style="width: 200px;" />
            </el-form-item>
            <el-form-item v-for="(item, index) in ruleForm.joinList" :key="item.type" :label="`${item.label}的价格`"
                :prop="`joinList.${index}.price`" :rules="[
                    { required: true, message: `请输入${item.label}的价格`, trigger: 'blur' }
                ]">
                <el-input v-model="item.price" type="number" @input="(val: any) => item.price = val < 0 ? 0 : val"
                    :placeholder="`请输入${item.label}的价格`" style="width: 200px;" />
            </el-form-item>
        </el-form>
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="handleClose">取 消</el-button>
                <el-button type="primary" @click="handleSubmit(ruleFormRef)">添 加</el-button>
            </div>
        </template>
    </el-dialog>
</template>

<script setup lang="ts">
import uploadStyle from '@/components/uploadStyle.vue'
import { globalHeaders } from "@/utils/request";

import type { FormInstance, UploadProps } from 'element-plus'

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const props = defineProps(['visible', 'initList']);
const emits = defineEmits(['submit', 'close', 'modify']);

const show = ref(false);
const baseUrl = import.meta.env.VITE_APP_BASE_API;
const uploadImgUrl = ref(baseUrl + "/resource/oss/upload");
const headers = ref(globalHeaders);
const type = ref('')

watch(() => props.visible, async (newValue) => {
    show.value = newValue
    if (newValue) {
        if (props.initList?.list && Object.keys(props.initList?.list).length > 0) {
            type.value = '1'
            ruleForm.value = props.initList?.list.item
        } else {
            type.value = ''
            ruleForm.value.joinList = props.initList?.volume_interval.map((item: any, index: number) => {
                return {
                    label: item.label,
                    type: item.value,
                    price: null,
                }
            })
        }
    }
}, { deep: true });

const ruleFormRef = ref<FormInstance>()
const ruleForm = ref<any>({
    attributeName: '',
    imageUrl: '',
    color: '',
    joinList: []
})
const fileTypes = ['image/png', 'image/jpeg']

const rules = reactive<any>({
    attributeName: [
        { required: true, message: '请输入材质名称', trigger: 'blur' },
    ],
    imageUrl: [
        { required: true, message: '请上传配件展示图', trigger: ['change', 'blur'] },
    ],
})

/**
 * 上传配件展示图格式的判定
 */
const beforedeSignSketchUpload: UploadProps['beforeUpload'] = (rawFile) => {
    if (!fileTypes.includes(rawFile.type)) {
        ElMessage.error('请上传jpg/png格式的图片')
        return false
    } else if (rawFile.size / 1024 / 1024 > 5) {
        ElMessage.error('图片不可超过 5MB!')
        return false
    }
    return true
};

/**
 * 上传配件展示图 成功回调
 */
const handleDesignSketchSuccess: UploadProps['onSuccess'] = (
    response,
    uploadFile
) => {
    console.log(response)
    ruleForm.value.imageUrl = response.data.url
};


const handleSubmit = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    await formEl.validate((valid, fields) => {
        if (valid) {
            const query = JSON.parse(JSON.stringify(ruleForm.value))
            if (type.value) {
                proxy?.$modal.msgSuccess('修改成功');
                emits('modify', {
                    index: props.initList?.list.index,
                    data: query
                });
            } else {
                proxy?.$modal.msgSuccess('添加成功');
                emits('submit', {
                    ...query,
                    attributeType: props.initList?.attributeType
                });
            }

            handleClose();
        } else {
            console.log('error submit!', fields)
        }
    })
}


const handleClose = () => {
    ruleFormRef.value?.resetFields();
    emits('close');
};

onMounted(() => {
})
</script>

<style lang="scss" scoped>
::v-deep .el-upload-dragger {
    padding: 0px 4px !important;
    height: 100px !important;
    width: 260px;
}

::v-deep .el-divider--horizontal {
    margin: 12px 0;
}
</style>